import React from 'react'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Button, message, Skeleton } from 'antd'
import moment from 'moment'
import BillTextBlock from './PayFee/BillTextBlock'
import BillBlock from './PayFee/BillBlock'
import PayBillBlock from './PayFee/PayBillBlock'
import style from './PayFee.module.less'
import { requestFiles } from '@js/request'
import { awaitWrap } from '@js/tool'
class PayFee extends Component {
  state = {
    bill: null,
    list: [],
    loading: false,
    editing: false,
    isDecide: false,
    isModify: false,
    dictionaries: {}
  }

  // 获取枚举的字典值
  getDictionary () {
    this.$get('/api/xapc/dictionary', {
      types: '交费单类型,交费情况'
    }).then(res => {
      if (res.status === 1) {
        // 设置枚举字典
        const dictionaries = this.formatDictionaries(res.data)
        this.setState({
          dictionaries
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 获取交费单列表
  getBills () {
    this.setState({ loading: true })
    this.$get('/api/xapc/bill', {
      caseid: this.props.caseDetail.id
    })
      .then(res => {
        this.setState({ loading: false })
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          list: res.data.list
        })
      }).catch(e => this.setState({ loading: true }))
  }

  cloneData (d) {
    return {
      ...d,
      create_datetime: d.create_datetime ? moment(d.create_datetime * 1000) : undefined,
      pay_datetime: d.pay_datetime ? moment(d.pay_datetime * 1000) : undefined,
      accept_datetime: d.accept_datetime ? moment(d.accept_datetime * 1000) : undefined
    }
  }

  setModify (d) {
    const bill = this.cloneData(d)
    this.setState({
      bill,
      isModify: true
    })
  }

  setDecide (d) {
    const bill = this.cloneData(d)
    if (!bill.pay_amount && bill.amount) {
      bill.pay_amount = bill.amount
    }
    if (!bill.payer_actual && bill.payer) {
      bill.payer_actual = bill.payer
    }
    if (!bill.payerid_actual && bill.payerid) {
      bill.payerid_actual = bill.payerid
    }
    this.setState({
      bill,
      isDecide: true
    })
  }

  // 取消
  cancelHandle () {
    this.setState({
      bill: null,
      isDecide: false,
      isModify: false
    })
  }

  // 请求
  onFinish (d) {
    const { isModify, isDecide } = this.state
    if (isDecide) {
      this.decideRequest(d)
    } else if (isModify) {
      if (d.id) {
        this.modifyRequest(d)
      } else {
        this.addRequest(d)
      }
    }
  }

  // 确定交费请求
  async decideRequest (d) {
    const hide = message.loading('提交中', 120)
    let fileid = ''
    const file = d.file ? d.file.fileList : []
    if (file.length) {
      const [e, d] = await awaitWrap(requestFiles(file))
      if (e) {
        return message.warning(e.message)
      }
      fileid = d.map(li => li.id).join()
    }
    d.billid = d.id
    d.fileid = fileid
    delete d.id
    delete d.file
    if (d.pay_datetime) {
      d.pay_datetime = Math.floor(d.pay_datetime / 1000)
    }
    if (!d.pay_type) {
      d.pay_type = '线下'
    }
    this.$put('/api/xapc/pay', {
      ...d
    }).then(res => {
      hide()
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      if (this.state.list.length === 1) {
        this.props.refreshCaseData()
      }
      this.setState({
        bill: null,
        isDecide: false
      })
      this.getBills()
    }).catch(() => hide())
  }

  // 修改收费单
  modifyRequest (d) {
    const hide = message.loading('提交中', 120)
    const id = d.id
    delete d.id
    this.$put(`/api/xapc/bill/${id}`, d)
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.getBills()
        this.setState({
          bill: null,
          isModify: false
        })
      }).catch(() => hide())
  }

  // 添加收费单请求
  addRequest (d) {
    const hide = message.loading('提交中', 120)
    this.$post('/api/xapc/bill', d)
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.getBills()
        this.setState({
          bill: null,
          isModify: false
        })
      }).catch(() => hide())
  }

  // 点击添加交费单
  createBill () {
    this.setState({
      bill: { caseid: this.props.caseDetail.id },
      isModify: true
    })
  }

  componentDidMount () {
    this.getDictionary()
    this.getBills()
  }

  // 渲染添加按钮
  renderAddMoreBtn () {
    const { isModify, isDecide, loading } = this.state
    if (isModify || isDecide || loading) {
      return null
    }
    return (
      <div className={style.block}>
        <Button disabled={!this.props.editable} type='dashed' block onClick={() => { this.createBill() }}>+ 添加交费单</Button>
      </div>
    )
  }

  // 渲染交费单列表
  renderList () {
    const { bill, isDecide, isModify, dictionaries } = this.state
    const { editable, caseDetail } = this.props
    const applicants = (caseDetail.applicants || []).filter(li => li.status)
    const respondents = (caseDetail.respondents || []).filter(li => li.status)
    const isPayTypes = dictionaries['交费情况'] || []
    const types = dictionaries['交费单类型'] || []
    const editing = isDecide || isModify
    return this.state.list.map(li => {
      if (!bill || li.id !== bill.id) {
        return (
          <div className={style.block} key={li.id}>
            <BillTextBlock data={li} editable={editable && !editing} applicants={applicants} respondents={respondents} modifyHandle={() => this.setModify(li)} decideHandle={() => this.setDecide(li)} />
          </div>
        )
      }
      if (bill && bill.id === li.id) {
        if (isDecide) {
          return (
            <div className={style.block} key={li.id}>
              <PayBillBlock data={bill} applicants={applicants} respondents={respondents} isPayTypes={isPayTypes} cancelHandle={() => this.cancelHandle()} onFinish={d => this.onFinish(d)} />
            </div>
          )
        }
        if (isModify) {
          return (
            <div className={style.block} key={li.id}>
              <BillBlock data={bill} applicants={applicants} respondents={respondents} types={types} cancelHandle={() => this.cancelHandle()} onFinish={d => this.onFinish(d)} />
            </div>
          )
        }
      }
    })
  }

  // 渲染添加模块
  renderAddBillBlock () {
    const { bill, isModify, dictionaries } = this.state
    const { caseDetail } = this.props
    const applicants = (caseDetail.applicants || []).filter(li => li.status)
    const respondents = (caseDetail.respondents || []).filter(li => li.status)
    const types = dictionaries['交费单类型'] || []
    if (isModify && !bill.id) {
      return (
        <div className={style.block}>
          <BillBlock data={bill} applicants={applicants} respondents={respondents} types={types} cancelHandle={() => this.cancelHandle()} onFinish={d => this.onFinish(d)} />
        </div>
      )
    }
  }

  render () {
    const { loading } = this.state
    return (
      <div>
        {loading ? <Skeleton active /> : null}
        {this.renderList()}
        {this.renderAddBillBlock()}
        {this.renderAddMoreBtn()}
      </div>
    )
  }
}

PayFee.propTypes = {
  caseDetail: PropTypes.object,
  // active: PropTypes.bool,
  // refreshCaseData: PropTypes.func,
  editable: PropTypes.bool
}
PayFee.defaultProps = {
  caseDetail: {},
  active: false,
  refreshCaseData: () => {},
  editable: false
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(PayFee)
